package com.jtlrm.ckd.mvp.view.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.base.sdk.base.net.CommonObserver;
import com.base.sdk.util.DateFormatUtil;
import com.jtlrm.ckd.R;
import com.jtlrm.ckd.base.acitvity.TitleBarActivity;
import com.jtlrm.ckd.entity.AddYinShiEntity;
import com.jtlrm.ckd.entity.ShiWuEntity;
import com.jtlrm.ckd.entity.ShiWuPicEntity;
import com.jtlrm.ckd.entity.YinShiDataEntity;
import com.jtlrm.ckd.entity.YinShiDetailAdpterEntity;
import com.jtlrm.ckd.entity.YinShiDetailEntity;
import com.jtlrm.ckd.entity.YinShiTuPianEntity;
import com.jtlrm.ckd.entity.YongCanTypeEntity;
import com.jtlrm.ckd.entity.event.YinShiDeleteMessage;
import com.jtlrm.ckd.entity.event.YinShiSelectMessage;
import com.jtlrm.ckd.entity.event.YinShiUpdateMessage;
import com.jtlrm.ckd.entity.submitEntity.AddYinShiData;
import com.jtlrm.ckd.entity.submitEntity.ChangeYinShiData;
import com.jtlrm.ckd.entity.submitEntity.YinShiData;
import com.jtlrm.ckd.mvp.model.YinShiMode;
import com.jtlrm.ckd.mvp.view.adapter.YinShiDetailAdapter;
import com.jtlrm.ckd.util.EventBusUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yanzhenjie.recyclerview.swipe.widget.DefaultItemDecoration;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.BindViews;

public class YinShidetailActivity extends TitleBarActivity implements View.OnClickListener {

    @BindView(R.id.title_date)
    TextView selectDateT;
    @BindViews({R.id.week7, R.id.week6, R.id.week5, R.id.week4, R.id.week3, R.id.week2, R.id.week1})
    List<TextView> weekTs;
    @BindViews({R.id.date7, R.id.date6, R.id.date5, R.id.date4, R.id.date3, R.id.date2, R.id.date1})
    List<TextView> dayTs;
    @BindViews({R.id.time7, R.id.time6, R.id.time5, R.id.time4, R.id.time3, R.id.time2, R.id.time1})
    List<LinearLayout> dateLs;
    ArrayList<YinShiDataEntity> yinShiBasics;
    int select = -1; // 选中的时间
    int initSelect; // 最开始选中的时间
    DateFormatUtil dateFormatUtil = new DateFormatUtil();
    YinShiMode yinShiMode;
    List<YongCanTypeEntity> yongCanTypeEntities;
    List<YinShiDetailEntity> yinShiDetailEntities;
    List<YinShiDetailAdpterEntity> adpterEntities = new ArrayList<>();
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    YinShiDetailAdapter adapter;
    String patientId;
    boolean isChanged = false; // 是否已修改
    List<YinShiTuPianEntity> tuPianEntities;
    boolean isFirst = true; // 是否是第一次进入app

    public static void goDetail(Context context, ArrayList<YinShiDataEntity> dates, int select, String patientId) {
        Intent intent = new Intent(context, YinShidetailActivity.class);
        intent.putParcelableArrayListExtra("dates", dates);
        intent.putExtra("select", select);
        intent.putExtra("patientId", patientId);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Intent intent = getIntent();
        yinShiBasics = intent.getParcelableArrayListExtra("dates");
        initSelect = intent.getIntExtra("select", 0);
        patientId = intent.getStringExtra("patientId");
        super.onCreate(savedInstanceState);
    }

    @Override
    protected String getTitleText() {
        return "饮食详情";
    }

    @Override
    protected void setContentLayout() {
        setContentView(R.layout.activity_yin_shidetail);
    }

    @Override
    protected void initView() {
        yinShiMode = new YinShiMode();
        adapter = new YinShiDetailAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.addItemDecoration(createItemDecoration());
        recyclerView.setAdapter(adapter);
        initDates();
        EventBusUtil.register(this);
    }


    @Override
    protected void obtainData() {
        // 获取用餐类型
        queryYongCanType();
    }

    @Override
    protected void initEvent() {
        for (int i = 0; i < dateLs.size(); i++) {
            dateLs.get(i).setTag(i);
            dateLs.get(i).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = (int) v.getTag();
                    adapter.setEdit(false);
                    updateSelectDate(position);
                }
            });
        }
        adapter.openLoadAnimation();
        smartRefreshLayout.setEnableLoadmore(false);
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                queryYongCanDetail();
            }
        });

        adapter.setPicClickListener(new YinShiDetailAdapter.PicClickListener() {
            @Override
            public void clickPic(String yongCanTypeId) {
                queryPic(yongCanTypeId);
            }
        });
    }

    private void queryPic(String yongCanTypeId) {
        showLoadingDialog("加载中");
        yinShiMode.queryYinShiPic(getCurrentYinShiId(), yongCanTypeId, new CommonObserver<List<ShiWuPicEntity>>() {
            @Override
            public void onError(int errType, String errMessage) {
                dismissLoadingDialog();
                showToast(errMessage);
            }

            @Override
            public void onResult(List<ShiWuPicEntity> data) {
                dismissLoadingDialog();
                ArrayList<String> pic = new ArrayList<>();
                for (ShiWuPicEntity entity : data) {
                    if (!TextUtils.isEmpty(entity.getDietImagePath())) {
                        pic.add(entity.getDietImagePath());
                    } else {
                        pic.add("");
                    }
                }
                if (pic.size() > 0) {
                    YinShiTuPianActivity.showTuPian(context, pic);
                } else {
                    showToast("暂无图片");
                }
            }
        }, lifecycleSubject);
    }


    @Override
    public void onClick(View v) {

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (isChanged) {
            EventBusUtil.postEvent(new YinShiUpdateMessage());
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBusUtil.unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(YinShiSelectMessage message) {
        if (message != null && message.getData() != null && message.getData().size() > 0) {
//            adapter.setEdit(false);
            if (notEmpty(getCurrentYinShiId())) {
                // 有数据只能修改
                changeUploadShiWu(message.getData());
                return;
            }
            // 没有数据可以增加
            addYinShiData(message.getData());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(YinShiDeleteMessage message) {
        if (message != null && notEmpty(message.getYinShiId())) {
            // 删除饮食
            deleteYinShi(message.getYinShiId());
        }
    }

    /**
     * 删除饮食
     *
     * @param yinShiId
     */
    private void deleteYinShi(String yinShiId) {
        isChanged = true;
        yinShiMode.deleteYinShi(yinShiId, new CommonObserver<String>() {
            @Override
            public void onError(int errType, String errMessage) {
                showToast(errMessage);
                smartRefreshLayout.autoRefresh();
            }

            @Override
            public void onResult(String data) {
                showToast("删除成功");
                smartRefreshLayout.autoRefresh();
            }
        }, lifecycleSubject);
    }


    /**
     * 修改数据
     *
     * @param list
     */
    private void changeUploadShiWu(List<YinShiData> list) {
        isChanged = true;
        ChangeYinShiData changeYinShiData = new ChangeYinShiData();
        changeYinShiData.setDietBodyId(getCurrentYinShiId());
        changeYinShiData.setDiets(list);
        yinShiMode.changeYinShi(changeYinShiData, new CommonObserver<String>() {

                    @Override
                    public void onError(int errType, String errMessage) {
                        showToast(errMessage);
                    }

                    @Override
                    public void onResult(String data) {
                        showToast("修改成功");
                        smartRefreshLayout.autoRefresh();
                    }
                }, lifecycleSubject
        );
    }

    /**
     * 新增饮食
     *
     * @param
     */
    public void addYinShiData(List<YinShiData> list) {
        isChanged = true;
        AddYinShiData addYinShiData = new AddYinShiData();
        addYinShiData.setPatientId(patientId);
        // 设置饮食时间
        addYinShiData.setDietTime(yinShiBasics.get(select).getBasicTime());
        addYinShiData.setDiets(list);
        yinShiMode.addYinShi(addYinShiData, new CommonObserver<AddYinShiEntity>() {
            @Override
            public void onError(int errType, String errMessage) {
                showToast(errMessage);
            }

            @Override
            public void onResult(AddYinShiEntity data) {
                // 将新增的id设置上去
                yinShiBasics.get(select).setId(data.getId() + "");
                smartRefreshLayout.autoRefresh();
                showToast("保存成功");
            }
        }, lifecycleSubject);

    }

    private void queryYongCanDetail() {
        if (select < 0 || select > (yinShiBasics.size() - 1)) {
            closeFrshorLoadmore();
            return;
        }
        yinShiMode.queryYinShiDetail(getCurrentYinShiId(), new CommonObserver<List<YinShiDetailEntity>>() {
            @Override
            public void onError(int errType, String errMessage) {
                showToast(errMessage);
                closeFrshorLoadmore();
            }

            @Override
            public void onResult(List<YinShiDetailEntity> data) {
                yinShiDetailEntities = data;
                queryTuPian();
            }
        }, lifecycleSubject);
    }

    private void queryTuPian() {
        yinShiMode.queryYinShiTuPian(getCurrentYinShiId(), new CommonObserver<List<YinShiTuPianEntity>>() {
            @Override
            public void onError(int errType, String errMessage) {
                showToast(errMessage);
                closeFrshorLoadmore();
            }

            @Override
            public void onResult(List<YinShiTuPianEntity> data) {
                tuPianEntities = data;
                updateAdapter();
                closeFrshorLoadmore();
            }
        }, lifecycleSubject);
    }


    public String getCurrentYinShiId() {
        return yinShiBasics.get(select).getId();
    }

    /**
     * 更新适配器数据
     */
    private void updateAdapter() {
        if (isFirst) {
            if (yinShiDetailEntities == null || yinShiDetailEntities.size() == 0) {
                setEditStatus(true);
            }
            isFirst = false;
        }

        if (yongCanTypeEntities != null && yinShiDetailEntities != null) {
            adpterEntities.clear();
            for (YongCanTypeEntity entity : yongCanTypeEntities) {
                YinShiDetailAdpterEntity adpterEntity = new YinShiDetailAdpterEntity();
                adpterEntity.setYongCanType(entity);
                // 饮食数据
                List<YinShiDetailEntity> yinShiList = new ArrayList<>();
                for (YinShiDetailEntity detailEntity : yinShiDetailEntities) {
                    if ((entity.getId() + "").equals(detailEntity.getHaveMealsTypeId() + "")) {
                        yinShiList.add(detailEntity);
                    }
                }
                for (YinShiTuPianEntity tuPianEntity : tuPianEntities) {
                    if ((entity.getId() + "").equals(tuPianEntity.getId() + "")) {
                        adpterEntity.setHasTuPian(tuPianEntity.getCount() != 0 ? true : false);
                    }
                }
                adpterEntity.setYinShiDetailEntities(yinShiList);
                adpterEntities.add(adpterEntity);
            }
            adapter.replaceData(adpterEntities);
        }
    }


    /**
     * 更新选中的时间
     *
     * @param position
     */
    private void updateSelectDate(int position) {
        titleBar.tvRight.setText("修改");
        if (position != select && select != -1) {
            // 以后选择的时候
            TextView day = dayTs.get(position);
            if (position != initSelect) {
                // 设置初始的状态
                dayTs.get(initSelect).setBackgroundResource(R.drawable.white_round_green_background);
                dayTs.get(initSelect).setTextColor(getResourceColor(R.color.white));
                weekTs.get(initSelect).setTextColor(getResourceColor(R.color.text_green3));
            }
            // 设置现在选中的颜色
            day.setBackgroundResource(R.drawable.white_circel_background);
            day.setTextColor(getResourceColor(R.color.text_green));
            weekTs.get(position).setTextColor(getResourceColor(R.color.white));

            // 恢复之前的状态
            if (select != initSelect) {
                dayTs.get(select).setBackgroundResource(R.color.text_green);
                dayTs.get(select).setTextColor(getResourceColor(R.color.text_green3));
                weekTs.get(select).setTextColor(getResourceColor(R.color.text_green3));
            }
            select = position;
            smartRefreshLayout.autoRefresh();
        } else if (select == -1) {
            // 第一次初始选择的时候
            dayTs.get(position).setBackgroundResource(R.drawable.white_circel_background);
            dayTs.get(position).setTextColor(getResourceColor(R.color.text_green));
            weekTs.get(position).setTextColor(getResourceColor(R.color.white));
            select = position;
            smartRefreshLayout.autoRefresh();
        }
        try {
            setText(selectDateT, DateFormatUtil.dateFormatLine(dateFormatUtil.lineFormat.parse(yinShiBasics.get(position).getBasicTime()).getTime()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }


    /**
     * 查询用餐类型
     */
    private void queryYongCanType() {
        yinShiMode.queryYongCanType(new CommonObserver<List<YongCanTypeEntity>>() {
            @Override
            public void onError(int errType, String errMessage) {
                showToast(errMessage);
            }

            @Override
            public void onResult(List<YongCanTypeEntity> data) {
                yongCanTypeEntities = data;
            }
        }, lifecycleSubject);

    }

    /**
     * 初始化时间组件
     */
    private void initDates() {
        if (yinShiBasics != null && yinShiBasics.size() == 7 && initSelect < 7) {
            try {
                for (int i = 0; i < 7; i++) {
                    YinShiDataEntity entity = yinShiBasics.get(i);
                    Calendar calendar = dateFormatUtil.getCalendar(entity.getBasicTime());
                    int position = i;
                    Locale.setDefault(Locale.CHINA);
                    setText(weekTs.get(position), dateFormatUtil.getWeek(calendar.get(Calendar.DAY_OF_WEEK) - 1));
                    setText(dayTs.get(position), calendar.get(Calendar.DAY_OF_MONTH) + "");
                }
                updateSelectDate(initSelect);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void initTitleBar() {
        super.initTitleBar();
        titleBar.btLeft.setImageResource(R.drawable.ease_mm_title_back);
        titleBar.tvRight.setText("修改");
        titleBar.tvRight.setVisibility(View.VISIBLE);
        titleBar.tvMiddle.setTextColor(getResourceColor(R.color.white));
        titleBar.tvRight.setTextColor(getResourceColor(R.color.white));
        titleBar.setBackground(getResourceColor(R.color.text_green));
        titleBar.tvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ((titleBar.tvRight.getText() + "").equals("修改")) {
                    // 此时处于修改状态
                    setEditStatus(true);
                } else {
                    // 此时处于不修改状态
                    setEditStatus(false);
                    save();
                }
            }
        });
    }

    private void setEditStatus(boolean isEdite) {
        if (isEdite) {
            titleBar.tvRight.setText("保存");
            adapter.setEdit(true);
        } else {
            adapter.setEdit(false);
            titleBar.tvRight.setText("修改");
        }
    }

    /**
     * 点击保存后的操作， 点击保存只进行修改当前界面修改的数据，不操作删除数据
     */
    private void save() {
        List<YinShiDetailAdpterEntity> list = adapter.getData();
        List<YinShiData> submit = new ArrayList<>();
        for (YinShiDetailAdpterEntity adpterEntity : list) {
            for (YinShiDetailEntity entity : adpterEntity.getYinShiDetailEntities()) {
                YinShiData yinShiData = new YinShiData();
                if (notEmpty(entity.getId())) {
                    yinShiData.setId(entity.getId());
                    yinShiData.setGram(entity.getGram());
                    yinShiData.setFoodId(entity.getFoodId());
                    yinShiData.setFoodTypeId(entity.getFoodTypeId());
                    yinShiData.setHaveMealsTypeId(entity.getHaveMealsTypeId());
                    submit.add(yinShiData);
                }
            }
        }
        changeUploadShiWu(submit);
    }

    /**
     * 关闭加载更多或者刷新
     */
    private void closeFrshorLoadmore() {
        if (smartRefreshLayout.isLoading()) {
            smartRefreshLayout.finishLoadmore();
        }
        if (smartRefreshLayout.isRefreshing()) {
            smartRefreshLayout.finishRefresh();
        }
    }


    protected RecyclerView.ItemDecoration createItemDecoration() {
        return new DefaultItemDecoration(ContextCompat.getColor(context, R.color.line_color), 2, 1, -1);
    }

}
